package com.yiphonenum.phonenumberapplication;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class AssetDatabaseOpenHelper {

    private static final String DB_NAME = "city.db";

    private Context context;

    public AssetDatabaseOpenHelper(Context context) {
        this.context = context;
    }

    public void openDatabase() {

        // 是否已初始化数据
        SharedPreferences sp = context.getSharedPreferences("profile", Context.MODE_PRIVATE);
        Boolean db_copied = sp.getBoolean("db_copied", false);
        //if (!dbFile.exists()) {
        if (!db_copied) {
            try {
                copyDatabase();
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("db_copied", true);
                editor.apply();
            } catch (IOException e) {
                e.printStackTrace();
                //throw new RuntimeException("Error creating source database", e);
            }
        }

        //return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
    }

    private void copyDatabase() throws IOException {
        File dbFile = context.getDatabasePath(DB_NAME);
        if (!dbFile.getParentFile().exists()) {
            if (dbFile.getParentFile().mkdirs() ) {
                if (!dbFile.createNewFile()) {
                    return;
                }
            }
        }

        InputStream is = context.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(dbFile);

        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }

        os.flush();
        os.close();
        is.close();
    }


    private String copyBundledRealmFile(InputStream inputStream, String outFileName) {
        try {
            File file = new File(context.getFilesDir(), outFileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, bytesRead);
            }
            outputStream.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//
}
